const Vue = require("vue");
const VueServerRenderer = require("vue-server-renderer");
const Koa = require("koa");
const Router = require("koa-router");

const fs = require("fs");
const path = require("path");
const chalk = require("chalk");
const vm = new Vue({
  data() {
    return {
      name: "vue-ssr-demo",
    };
  },
  template: `<div>{{name}}</div>`,
});

const app = new Koa();
const router = new Router();
app.use(router.routes());

const template = fs.readFileSync(path.resolve(__dirname, "template.html"), "utf8");

router.get("/", async (ctx) => {
  // console.log("ctx", ctx);
  let render = VueServerRenderer.createRenderer({
    template,
  });
  let content = await render.renderToString(vm); // 接收 vm 和 回调两个参数
  console.log("content---", content);
  ctx.body = content;
});

app.listen(3000, () => {
  console.log(chalk.bold.red("app is running at port 3000"));
});
